package com.hs.srm.admin.modules.orders.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.common.util.StringUtils;
import com.hs.srm.admin.modules.harmfulsubstance.entity.EnvironCommitmentEntity;
import com.hs.srm.admin.modules.orders.entity.ScmPoHeaderEntity;
import com.hs.srm.admin.modules.orders.entity.ScmPoItemEntity;
import com.hs.srm.admin.modules.orders.service.ScmPoHeaderService;
import com.hs.srm.admin.modules.orders.service.ScmPoItemService;
import com.hs.srm.admin.modules.orders.vo.ScmPoItemVo;
import com.hs.srm.admin.modules.requisition.entity.SampleOrderReportEntity;
import com.hs.srm.admin.modules.requisition.service.SampleOrderReportService;
import com.hs.srm.admin.modules.sampletest.entity.UploadFileRemarkEntity;
import com.hs.srm.admin.modules.sampletest.service.SampleScmPoItemService;
import com.hs.srm.admin.modules.sampletest.service.UploadFileRemarkService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.DateUtils;
import com.hs.srm.common.utils.PageUtils;
import com.hs.srm.common.utils.R;
import com.hs.srm.tools.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sunnykid.text.SunnykidText;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author socik
 * @date 2019/7/1 14:49
 * @email socik@qq.com
 */
@Controller
@RequestMapping("/samplePoController")
public class SamplePoController extends AbstractController {

    @Value("${hssrm.file-upload-path}")
    protected String fileUploadPath;

    @Autowired
    private ScmPoItemService scmPoItemService;

    @Autowired
    private ScmPoHeaderService scPoHeaderService;
    @Autowired
    private SampleOrderReportService sampleOrderReportService;
    @Autowired
    private UploadFileRemarkService uploadFileRemarkService;


    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        if (username.getDeptId() == 13) {
            params.put("username", username.getUsername());
        }
        PageUtils pu = this.scmPoItemService.selectDetailPage(params);
        //非生产性订单不用valToTxt
        String poFlag = null;
        if (org.apache.commons.lang3.StringUtils.isNotBlank((CharSequence) params.get("poFlag"))) {
            poFlag = params.get("poFlag").toString();
        }
        if (!"NPRO".equals(poFlag)) {
            List<ScmPoItemVo> voList = (List<ScmPoItemVo>) pu.getList();
            voList = EntityUtils.valToTxt(voList);
            pu.setList(voList);
        }
        return R.ok(pu);
    }


    //样品试用报告汇总
    @RequestMapping("/samplelist")
    @ResponseBody
    public R samplelist(@RequestParam Map<String, Object> params) {
        SysUserEntity username = this.getUser();
        PageUtils pu = this.sampleOrderReportService.selectDetailPage(params);
        return R.ok(pu);
    }

    @RequestMapping("/add")
    @ResponseBody
    public R add(String datalist) {
        //获取登陆人信息
        SysUserEntity username = this.getUser();        //组装json数组
        JSONObject jsonObject = JSONObject.parseObject(datalist);
        String itemData = jsonObject.getString("items");
        String headData = jsonObject.getString("heads");
        JSONArray itemDataArray = JSONArray.parseArray(itemData);
        JSONArray headDataArray = JSONArray.parseArray(headData);
        int suffix = 0;
        //2.查询最大订单号
        int edition = 0;
        /**************订单号生成*****************/
        //1.查询最大订单号
        String poNo = this.scPoHeaderService.selectnum();
        //解析转换行项目
        List<ScmPoItemEntity> scmPoItemEntitys = itemDataArray.toJavaList(ScmPoItemEntity.class);
        //解析转换为采购订单头部信息
        List<ScmPoHeaderEntity> scmPoHeaderEntitys = headDataArray.toJavaList(ScmPoHeaderEntity.class);
        String po_no = "";
        if ("".equals(poNo) || poNo == null) {
            suffix = 0;
            edition = 0;
        } else {
            suffix = Integer.parseInt(poNo.substring(3));
            edition = this.scPoHeaderService.getEdition();
        }
        // 看版本号是否和查出来的一至
        if (suffix == edition) {
            edition++;
            suffix++;
            po_no = StringUtils.makeStr("488", suffix, 7).replaceAll(" ", "0");
        }
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        for (ScmPoHeaderEntity scmPoHeaderEntity : scmPoHeaderEntitys) {
            scmPoHeaderEntity.setPoId(uuid);
            scmPoHeaderEntity.setPoNo(po_no);
            scmPoHeaderEntity.setPoFlag("SPRO");
            scmPoHeaderEntity.setPoType("ZBZ");
            scmPoHeaderEntity.setCreatedBy(username.getUsername());
            scmPoHeaderEntity.setCreationDate(DateUtils.currentTimestamp());
            scmPoHeaderEntity.setEdition(edition);
            this.scPoHeaderService.insert(scmPoHeaderEntity);
        }
        int i = 1;
        for (ScmPoItemEntity scmPoItemEntity : scmPoItemEntitys) {
            String uuidItem = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            scmPoItemEntity.setItemNo("000" + i + "0");
            scmPoItemEntity.setPoItemId(uuidItem);
            scmPoItemEntity.setItemUuid(uuid);
            scmPoItemEntity.setPoNo(po_no);
            scmPoItemEntity.setCreatedBy(username.getUsername());
            scmPoItemEntity.setCreationDate(DateUtils.currentTimestamp());
            this.scmPoItemService.insert(scmPoItemEntity);
            i++;
        }

        return R.ok(po_no);
    }

    /**
     * 查看试用报告
     *
     * @param
     * @return
     */
    @RequestMapping("/tryOut")
    public ModelAndView toEdit(@RequestParam("pkId") String pkId) {
        ModelAndView modelAndView = new ModelAndView("modules/vendor/sample_order_trial_report");
        ScmPoItemEntity scmPoItemEntity = this.scmPoItemService.selectById(pkId);
        ScmPoHeaderEntity headerEntity = this.scPoHeaderService.selectOne(new EntityWrapper<ScmPoHeaderEntity>().eq("po_no", scmPoItemEntity.getPoNo()));
        SampleOrderReportEntity sampleOrderReportEntity1 = this.sampleOrderReportService.selectById(pkId);
        List<UploadFileRemarkEntity> uploadFileRemarkEntities = this.uploadFileRemarkService.selectList(new EntityWrapper<UploadFileRemarkEntity>().eq("po_item_id", pkId));
        modelAndView.addObject("upload", uploadFileRemarkEntities);
        if (sampleOrderReportEntity1 != null) {
            modelAndView.addObject("items", sampleOrderReportEntity1);
        } else {
            SampleOrderReportEntity sampleOrderReportEntity = new SampleOrderReportEntity();
            sampleOrderReportEntity.setReason(scmPoItemEntity.getReason());
            sampleOrderReportEntity.setCreationDate(new Date());
            sampleOrderReportEntity.setMaterialCode(scmPoItemEntity.getMaterialCode());
            sampleOrderReportEntity.setMaterialDesc(scmPoItemEntity.getMaterialDesc());
            sampleOrderReportEntity.setVendorCode(headerEntity.getVendorId());
            sampleOrderReportEntity.setVendorName(headerEntity.getCompanyName());
            sampleOrderReportEntity.setCount(scmPoItemEntity.getPoCount());
            sampleOrderReportEntity.setSpecification(scmPoItemEntity.getSpecification());
            sampleOrderReportEntity.setSectionSupervisor(headerEntity.getSectionSupervisor());
            sampleOrderReportEntity.setApply(scmPoItemEntity.getCreatedBy());
            sampleOrderReportEntity.setMeasureUnit(scmPoItemEntity.getPoUnit());
            sampleOrderReportEntity.setPkId(pkId);
            sampleOrderReportEntity.setDDate(new Date());
            if (headerEntity.getPoFlag().equals("NPRO")) {
                sampleOrderReportEntity.setMaterialCode(" ");
            }
            modelAndView.addObject("items", sampleOrderReportEntity);
            this.sampleOrderReportService.insert(sampleOrderReportEntity);
        }
        return modelAndView;
    }


    /**
     * 根据id和文件类型下载文件
     */
    /**
     * 根据id下载附件
     */
    @RequestMapping("/downloadFileById")
    public void downloadFileById(String poItemId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        List<UploadFileRemarkEntity> uploadFileRemarkEntities = this.uploadFileRemarkService.selectList(new EntityWrapper<UploadFileRemarkEntity>().eq("po_item_id", poItemId));
        for (UploadFileRemarkEntity uploadFileRemarkEntity : uploadFileRemarkEntities) {
            String fileType = uploadFileRemarkEntity.getFileType();
            UploadFileRemarkEntity uploadFileRemarkEntity1 = this.uploadFileRemarkService.selectOne(new EntityWrapper<UploadFileRemarkEntity>().eq("po_item_id", poItemId).eq("file_type", fileType));
            File file = new File(uploadFileRemarkEntity1.getFilepath());
            FileUtils.fileDownload(file, request, response);
        }
    }

}
